package com.mutual.help.controller;

import com.mutual.help.common.PageResult;
import com.mutual.help.entity.Users;
import com.mutual.help.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping("/loginPage")
    public String loginPage(){
        return "login";
    }

    /**
     * 登录shiro认证
     */
    @RequestMapping("/login")
    @ResponseBody
    public PageResult login(HttpServletRequest request, HttpSession session){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        try {
            userService.checkLogin(username,password);
        } catch (UnknownAccountException e) {
            return new PageResult("用户名不存在", 500);
        } catch (AuthenticationException e) {
            return new PageResult("账号或密码错误", 500);
        } catch (AuthorizationException e) {
            return new PageResult("没有权限", 500);
        } catch (Exception e) {
            return new PageResult("未知错误", 500);
        }
        Users user = userService.selectUserByUserName(username);
        session.setAttribute("user",user);
        return new PageResult("登录成功", 200);
    }

}
